"""
PROJECT: code
FILE: django_utlis.py
AUTHOR: wensen
CREATE: 2021-11-12
封装的Django通用类
"""
import time
import uuid
from django.core.cache import cache
from rest_framework.exceptions import ParseError
from rest_framework.pagination import PageNumberPagination
from django.utils.deprecation import MiddlewareMixin
from django.db import models
from rest_framework.response import Response


class APIResponse(Response):
    def __init__(self, code=2000, msg="操作成功！", data=None, status=200, headers=None, **kwargs):
        if data is None:
            data = {}
        response_data = {
            "code": code,
            "msg": msg,
            "data": data
        }
        response_data.update(kwargs)
        super().__init__(data=response_data, status=status, headers=headers)


# 分页器
class ResultsSetPagination(PageNumberPagination):
    page_size_query_param = 'page_size'  # 默认没有 自己配置
    max_page_size = 100  # 最大请求数据


# 验证手机验证码
def check_verification_code(suid, verification_code, cellphone):
    """
    缓存中读取验证码，并对比
    :param suid: 缓存key + “-” + 手机号码
    :param verification_code: 验证码
    :param cellphone: 手机号码
    :return:
    """
    cache_code = cache.get(suid)
    if suid is None:
        raise ParseError({"msg": "请传入suid！"})
    phone = suid.split("-")[1]
    if phone != cellphone:
        raise ParseError("提交的手机号与接收验证码的手机号不一致！")
    if cache_code is None:
        raise ParseError({"msg": "验证码过期！"})
    if str(verification_code) != str(cache_code):
        # python != 判断时会判断数据类型
        raise ParseError({"msg": "验证码错误！"})


class TokenMiddleware(MiddlewareMixin):
    """
    自定义的中间件
    """

    def process_request(self, request):
        """
        请求到来之前
        :param request:
        :return:
        """
        request.start_time = time.time()

    def process_response(self, request, response):
        """
        请求处理之后
        :param request:
        :param response:
        :return:
        """
        duration = time.time() - request.start_time
        response["X-Page-Duration-ms"] = int(duration * 1000)
        return response


def generate_uuid():
    """
    uuid4 + 毫秒级时间戳
    :return:
    """
    uid = str(uuid.uuid4()) + str(int(time.time() * 1000))
    suid = ''.join(uid.split('-'))
    return suid


class BaseModel(models.Model):
    """
    模型抽象基类
    """
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间", editable=False)
    update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间", editable=False)
    is_delete = models.BooleanField(default=False, verbose_name="删除标记")
    UUID = models.CharField(verbose_name="唯一ID", max_length=50, default=generate_uuid, editable=False)

    class Meta:
        abstract = True
